package io.adrainty.gbatis.transation;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;

/**
 * JDBC事物管理器
 * @author adrainty
 * @version v1.0.0
 * @since 2024/1/14 22:40
 */
public class JdbcTransaction implements Transaction {

    /**
     * 数据源
     */
    private final DataSource dataSource;

    /**
     * 自动提交标志
     */
    @SuppressWarnings("unused")
    private final boolean autoCommit;

    /**
     * 当前连接
     */
    private Connection connection;

    public JdbcTransaction(DataSource dataSource) {
        this(dataSource, false);
    }

    public JdbcTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }

    @Override
    public Connection getConnection() {
        return this.connection;
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    @Override
    public void openConnection() throws SQLException {
        connection = Objects.requireNonNullElse(connection, dataSource.getConnection());
        connection.setAutoCommit(autoCommit);
    }
}
